var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
var displayObj = convertEnumToObj(displayList);
var storeObj = convertEnumToObj(storeList);
var materialObj = convertEnumToObj(materialList);
var weightBillObj = convertEnumToObj(weightBillList);
var breedTypeObj = convertEnumToObj(breedTypeList);
var materialTypeObj = convertEnumToObj(materialTypeList);
layui.use(['laypage', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    $(".startTime").datePicker({
        format:"YYYY-MM",
        singleDate:true,  //单选日期
    });
    $(".endTime").datePicker({
        format:"YYYY-MM",
        singleDate:true,  //单选日期
    });
    // $(".update-today").datePicker({
    //     format:"YYYY-MM",
    //     singleDate:true,  //单选日期
    // });

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgName', title: '公司', width: 90, fixed: 'left', align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'code', title: '材料编码', width:140, fixed: 'left', align: 'center'}
            ,{field: 'name', title: '材料名称', width: 140, fixed: 'left', align: 'center'}
            ,{field: 'norms', title: '规格', width:140, fixed: 'left', align: 'center'}
            ,{field: 'nameNorms', title: '全称', width:180, fixed: 'left', align: 'center'}
            ,{field: 'type', title: '材料分类', width:120, align: 'center',templet:function (val) {
                if (val.type < 0)
                    return '';
                else
                    return materialTypeObj[val.type];
            }}
            ,{field: 'breedType', title: '工控分类', width:120, align: 'center', templet:function (val) {
                if (val.breedType == null)
                    return '';
                else {
                    if (isNull(breedTypeObj[val.breedType]))
                        return '';
                    else
                        return breedTypeObj[val.breedType];
                }
            }}
            ,{field: 'parentId', title: '材料上级', width:120, align: 'center', templet:function (val) {
                if (val.parentId < 1)
                    return '';
                else
                    return materialObj[val.parentId];
            }}
            ,{field: 'isDisplay', title: '过磅显示', width:120, align: 'center', templet:function (val) {
                if (val.isDisplay == null)
                    return '';
                else
                    return displayObj[val.isDisplay];
            }}
            ,{field: 'storeType', title: '仓位类型', width:120, align: 'center', templet:function (val) {
                if (val.storeType == null)
                    return '';
                else {
                    if (isNull(storeObj[val.storeType]))
                        return '';
                    else
                        return storeObj[val.storeType];
                }
            }}
            ,{field: 'billWeightType', title: '结算重量类型', width:120, align: 'center', templet:function (val) {
                if (val.billWeightType == null)
                    return '';
                else {
                    if (isNull(weightBillObj[val.billWeightType]))
                        return '';
                    else
                        return weightBillObj[val.billWeightType];
                }
            }}
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 240, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 150, align:'center', templet:function (val) {
                var str = '';
                // if (val.status == 0)
                //     str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                // else
                //     str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-normal">启用</a>';
                // str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/main-material/page'
        ,method: 'post'
        ,page: true
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
            materialId:$('.search-material').val()
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res)
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要删除？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option = {
                    id: id,
                    status: updateStatus
                };
                save(option, "/main-material/update-status/" + id);
            }, function(index){

            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            $('.updateModal').show();
            $('.updateModal .update-origin').val(data.orgId);
            $('.updateModal .update-material').val(data.materialId);
            $('.updateModal .update-nameNorms').val(data.nameNorms);
            $('.updateModal .update-code').val(data.code);
            $('.updateModal .update-norms').val(data.norms);
            // $('.updateModal .update-material').val(data.mid);
            $('.updateModal .update-type').val(materialTypeObj[data.type]);
            $('.updateModal .update-parentId').val(data.parentId);
            $('.updateModal .update-store').val(data.storeType);
            $('.updateModal .update-display').val(data.isDisplay);
            $('.updateModal .remark').val(data.remark);
            form.render();
        }
    });

    // form.on('select(search-today)', function(data) {
    //     $(".btn-query").trigger("click");
    // });
    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-material)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-storeType)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-type)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(add-material)', function(data) {
        var code = $.trim($(".addModal .add-material").find("option:selected").attr('data-code'));//
        var type = $.trim($(".addModal .add-material").find("option:selected").attr('data-type'));//
        var norms = $.trim($(".addModal .add-material").find("option:selected").attr('data-norms'));//
        var nameNorms = $.trim($(".addModal .add-material").find("option:selected").text());
        console.log(type)
        var typeStr = materialTypeObj[type];
        $('.addModal .add-code').val(code);
        $('.addModal .add-type').val(typeStr);
        $('.addModal .add-norms').val(norms);
        $('.addModal .add-nameNorms').val(nameNorms);
    });
    form.on('select(update-material)', function(data) {
        var code = $.trim($(".updateModal .update-material").find("option:selected").attr('data-code'));//
        var type = $.trim($(".updateModal .update-material").find("option:selected").attr('data-type'));//
        var norms = $.trim($(".updateModal .update-material").find("option:selected").attr('data-norms'));//
        var nameNorms = $.trim($(".updateModal .update-material").find("option:selected").text());
        var typeStr = materialTypeObj[type];
        console.log(type)
        $('.updateModal .update-code').val(code);
        $('.updateModal .update-type').val(typeStr);
        $('.updateModal .update-norms').val(norms);
        $('.updateModal .update-nameNorms').val(nameNorms);
    });
    $('.btn-query').on('click', function () {//搜索按钮
        var status = $('.search-status').val();
        var searchVal = $('.search-text').val();
        var orgId = $('.search-origin').val();
        var type = $('.search-type').val();
        var storeType = $('.search-storeType').val();
        var materialId = $('.search-material').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(materialId))
            option['materialId'] = materialId;
        if (!isNull(type))
            option['type'] = type;
        if (!isNull(storeType))
            option['storeType'] = storeType;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        console.log(option)
        table.reload('body-list', {
            where: option
        });
    });

    $('.btn-add').on('click', function () {
        if (isInsert == 0) {
            layer.msg('您无操作权限');
            return ;
        }
        $('.addModal').show();
    });
    $('.btn-refund').on('click', function () {
        $('.refundModal').show();
    });
    $(".addModal .close").on("click", function() {
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });
    $(".updateModal .close").on("click", function() {
        $(".updateModal").hide();
        $(".updateModal input").val("");
        $(".updateModal select").val("");
        $(".updateModal textarea").val("");
        form.render();
        tid = -1;
    });
    form.on('submit(updateBtns)', function() {
        var orgName = $.trim($(".updateModal .update-origin").find("option:selected").text());//公司
        var orgId = $.trim($(".updateModal .update-origin").val());//公司
        var remark = $.trim($(".updateModal .remark").val());//备注
        var materialId = $.trim($(".updateModal .update-material").val());//
        var isDisplay = $.trim($(".updateModal .update-display").val());//
        var storeType = $.trim($(".updateModal .update-store").val());//
        var parentId = $.trim($(".updateModal .update-parentId").val());//
        var breedType = $.trim($(".updateModal .update-breedType").val());//
        var weightBillType = $.trim($(".updateModal .update-weightBillType").val());//
        var name = $.trim($(".updateModal .update-material").find("option:selected").text());//
        var code = $.trim($(".updateModal .update-material").find("option:selected").attr('data-code'));//
        var type = $.trim($(".updateModal .update-material").find("option:selected").attr('data-type'));//
        var norms = $.trim($(".updateModal .update-material").find("option:selected").attr('data-norms'));//
        var nameNorms = $.trim($(".updateModal .update-material").find("option:selected").text());//
        var options = {id:tid,
            orgName:orgName,orgId:orgId,materialId:materialId,remark:remark,name:name,code:code,type:type,
            norms:norms,nameNorms:nameNorms,parentId:parentId,storeType:storeType,isDisplay:isDisplay,breedType:breedType,
            weightBillType:weightBillType
        };
        console.log(options)
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        if (isNull(orgId)) {
            layer.msg("请选择材料所属公司！");
            return ;
        }
        if (materialId == null) {
            layer.msg("请选择材料信息！");
            return ;
        }
        save(options, "/main-material/update/" + tid);
    });

    //点击添加提交
    form.on('submit(addBtns)', function() {
        var orgName = $.trim($(".addModal .add-origin").find("option:selected").text());//公司
        var orgId = $.trim($(".addModal .add-origin").val());//公司
        var remark = $.trim($(".addModal .remark").val());//备注
        var materialId = $.trim($(".addModal .add-material").val());//
        var isDisplay = $.trim($(".addModal .add-display").val());//
        var storeType = $.trim($(".addModal .add-store").val());//
        var parentId = $.trim($(".addModal .add-parentId").val());//
        var breedType = $.trim($(".addModal .add-breedType").val());//
        var weightBillType = $.trim($(".addModal .add-weightBillType").val());//
        var name = $.trim($(".addModal .add-material").find("option:selected").text());//
        var code = $.trim($(".addModal .add-material").find("option:selected").attr('data-code'));//
        var type = $.trim($(".addModal .add-material").find("option:selected").attr('data-type'));//
        var norms = $.trim($(".addModal .add-material").find("option:selected").attr('data-norms'));//
        var nameNorms = $.trim($(".addModal .add-material").find("option:selected").text());//
        var options = {id:tid,
            orgName:orgName,orgId:orgId,materialId:materialId,remark:remark,name:name,code:code,type:type,
            norms:norms,nameNorms:nameNorms,parentId:parentId,storeType:storeType,isDisplay:isDisplay,
            weightBillType:weightBillType,breedType:breedType
        };
        console.log(options)
        if (isNull(orgId)) {
            layer.msg("请选择材料所属公司！");
            return ;
        }
        if (materialId == null) {
            layer.msg("请选择材料信息！");
            return ;
        }
        save(options, "/main-material/save");
    });

    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'put',
            dataType: 'json',
            data:option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("更新成功!");
                    table.reload('body-list', { where: {offset: 0,page:1,
                            limit: limit,
                            orgId:$('.search-origin').val(),
                            materialId:$('.search-material').val(),
                            type:$('.search-type').val(),
                            status:$('.search-status').val(),
                            storeType:$('.search-storeType').val()} });
                    $(".addModal").hide();
                    $(".addModal input").val("");
                    $(".addModal select").val("");
                    $(".addModal textarea").val("");
                    $(".updateModal").hide();
                    $(".updateModal input").val("");
                    $(".updateModal select").val("");
                    $(".updateModal textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
});